<?php

namespace app\controller\wechat_min;

use app\common\controller\WechatController;
use app\common\model\platform\PlatformApp;
use app\common\model\platform\PlatformAppOpen;
use EasyWeChat\Factory;
use EasyWeChat\OpenPlatform\Server\Guard;
use hiduoke\services\douyinMinApp\API\DouyinOpenApi;
use hiduoke\services\douyinMinApp\DouyinMinAppServer;
use hiduoke\services\wechatMinApp\WechatMinAppServer;
use think\App;

class Open extends WechatController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function index()
    {
        return $this->success('抖音小程序服务商平台接口');
    }

    public function test()
    {
        $WxServer = new WechatMinAppServer(0);
        $res = $WxServer->getOpenApi()->getPreAuthorizationUrl('http://vue3.heiduoke.cn/wxmin/open/callback?appid=0');
//        echo "<a href='" . $res . "' target='_blank'>测试</a>";
        $res = $WxServer->getOpenApi()->code_template->list();
        dump($res);
        // 打印执行步骤，也就是php的文件
        $WxServer->getOpenApi()->miniProgram('')->code->commit($templateId, $extJson, $version, $description);

    }

    public function callback()
    {
        $appid = input('appid', 0);
        $auth_code = input('auth_code', '');
        $WxServer = new WechatMinAppServer($appid);
        $res = $WxServer->getOpenApi()->handleAuthorize($auth_code);
        $authorization_info = $res['authorization_info'] ?? [];
        if ($authorization_info) {
            $app = (new PlatformApp())->where(['id' => $appid])->find();
            if ($app) {
                unset($authorization_info['func_info']);
                // 可能是有选择的
                $authorization_info['auth_type'] = 1;
                // 标记为授权
                $app->other_data = $authorization_info;
                $app->appid = $authorization_info['authorizer_appid'];
                $app->server_config = $authorization_info;
                $app->auth_type = 'open';
                $app->save();
                // 授权成功
                showMessage('授权成功,请关闭当前页面', 'success', '', 200, ['auto_jump' => false, 'show_btn' => false]);
            }
        }
        showMessage('授权失败', 'error', '', -1, ['auto_jump' => false, 'show_btn' => false]);
    }

    /**
     * 授权事件接收 URL
     * Create by :  刘泓宾<514660094@qq.com>
     * @return string|\think\response\Json
     */
    public function event()
    {
        $id = input('id', 0);
        debug('aaaa', input());
        $open = (new \app\common\model\open\Open())->where(['id' => $id])->find();
        if ($open) {
            $openAPI = Factory::openPlatform($open['config']);
            $server = $openAPI->server;
            return $server->serve();
        } else {
            return json(['code' => 0, 'msg' => '授权信息不存在']);
        }
    }

    /**
     * Create by :  刘泓宾<514660094@qq.com>
     * @return string
     */
    public function call_back()
    {
        $authorization_code = input('authorization_code', '');
        $platform_app_id = input('appid', 0);
        $DYServer = new DouyinMinAppServer($platform_app_id);
        $res = $DYServer->getOpenApi()->getAuthorizerAccessToken($DYServer->component_access_token, $authorization_code);
        if (isset($res['errno'])) {
            return showMessage($res['message'], 'error', ['show_btn' => false, 'second' => -1]);
        }
        $platform_app = $DYServer->getPlatformApp();
        $platform_app->other_data = $res;
        $platform_app->server_config = [
            'auth_type'        => 1,
            'authorizer_appid' => $res['authorizer_appid'],
        ];
        $platform_app['appid'] = $res['authorizer_appid'];
        $platform_app->save();
        return showMessage('授权成功,请关闭当前页面', 'success', '', 0,
            ['show_btn' => false, 'second' => -1, 'title' => '授权成功,请关闭当前页面']);
    }


    /**
     * // TODO 目前感觉没对接
     * 消息与事件接收 URL
     */
    public function message_event()
    {
        debug("message_event", input());
        $id = input('id', 0);
        $open = (new \app\common\model\open\Open())->where(['id' => $id])->find();
        if ($open) {
            $openAPI = Factory::openPlatform($open['config']);
            $server = $openAPI->miniProgram(input('appid'))->server;
            $server->push(function ($message) {
                debug("message_event2", $message);
                return "success";
            });
            return $server->serve();
        } else {
            return json(['code' => 0, 'msg' => '授权信息不存在']);
        }
    }
}
